<?php
/**取模的哈希分布式服务器算法
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/25/025
 * Time: 16:11
 */



class ModerHasher implements \hasher, \distribution
{
    protected $_ser = [];
    protected $_num = 0;

    public function _hash($str)
    {
        return sprintf('%u', crc32($str));
    }

    public function lookup($key)
    {
        $index = $this->_hash($key) % $this->_num;
        return $this->_ser[$index];
    }

    public function addNode($s)
    {
        $this->_ser[] = $s;
        $this->_num += 1;
    }

    public function delNode($s)
    {
        foreach ($this->_ser as $key => $v) {
            if ($s == $v) {
                unset($this->_ser[$key]);
            }
        }
        $this->_num -= 1;
        $this->_ser = array_merge($this->_ser);
    }

}


